package com.example.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;


@Configuration
public class DruidConfig {
	@Bean
	public DataSource druidDataSource(
	                 @Value("${spring.datasource.driver-class-name}") String driver,
	                 @Value("${spring.datasource.url}") String url,
	                 @Value("${spring.datasource.username}") String username,
	                 @Value("${spring.datasource.password}") String password) {
	        DruidDataSource druidDataSource = new DruidDataSource();
	        druidDataSource.setDriverClassName(driver);
	        druidDataSource.setUrl(url);
	        druidDataSource.setUsername(username);
	        druidDataSource.setPassword(password);
	        try {
	            druidDataSource.setFilters("stat, wall, slf4j");
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }
	        return druidDataSource;
	}
	
	/**
	 * 输出可执行的SQL
	 * @return
	 */
	@Bean
	public Slf4jLogFilter slf4jLogFilter(){
		Slf4jLogFilter filter = new Slf4jLogFilter();
		filter.setStatementExecutableSqlLogEnable(true);
		return filter;
	}
	
	@Bean(name="druid-stat-interceptor")
	public DruidStatInterceptor druidStatInterceptor() {
		DruidStatInterceptor interceptor = new DruidStatInterceptor();
		return interceptor;
	}
	
	@Bean
	public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
		BeanNameAutoProxyCreator autoProxyCreator = new BeanNameAutoProxyCreator();
		autoProxyCreator.setProxyTargetClass(true);
		String[] beanNames = {"*Mapper","*ServiceImpl","*Controller"};
		autoProxyCreator.setBeanNames(beanNames);
		String[] interceptorNames = {"druid-stat-interceptor"};
		autoProxyCreator.setInterceptorNames(interceptorNames);
		return autoProxyCreator;
	}
}